package cn.tedu.util;

import java.io.*;

//测试 读一行写一行
public class IOUtils {
    //读一行BufferedReader写一行PrintWriter
    public static void method3() {
        //声明变量,方便finally语句块使用
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            //1,创建对象
            in = new BufferedReader(new FileReader("D:\\iotest\\1.txt"));
            out = new PrintWriter(new FileWriter("D:\\iotest\\2.txt"));
            //2,开始读写
            String  line = "" ;//定义变量,记录读到的这一行数据
            while(line != null){//只要有数据就读,没数据就返回null
                line = in.readLine() ;//一行一行的读
                out.println(line);//读一行就写出一行
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {//保证资源一定会被释放
            //3,释放资源
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 写一行:PrintWriter
     * 参数:
     * String path -- 要把数据写出到哪个文件里去
     * String data  -- 要写出什么数据
     */
    public static void writeLine(String path,String data) throws IOException {
        //1,创建对象
        PrintWriter writer = new PrintWriter(new FileWriter(path));
        //2,写出一行数据
        writer.println(data);
        //3,释放资源
        writer.close();//作用:flush()+close()
    }
    /**
     * 用来读一行:BufferedReader
     * String path -- 要读取文件的路径
     */
    public static void readLine(String path) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader(path)) ;
        //读不到数据时,readLine()返回null
//        String line = reader.readLine() ;
//        System.out.println("line = " + line);
        String line = "" ;//创建变量,记录读取到的一行数据
        while( ( line= reader.readLine() )!= null){//只要有数据,就一直读,没数据就返回null
            //一行一行读取数据
            System.out.println("line = " + line);
        }
    }
}
